/**
 *  (c)
 *
 *
 *
 *
 */

package com.nn.smart.bus.commons.tools.security.user;

import com.nn.smart.bus.commons.tools.constant.Constant;
import com.nn.smart.bus.commons.tools.redis.UserDetailRedis;
import com.nn.smart.bus.commons.tools.utils.HttpContextUtils;
import com.nn.smart.bus.commons.tools.utils.SpringContextUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户
 */
public class SecurityUser {
    private static UserDetailRedis userDetailRedis;
    static {
        userDetailRedis = SpringContextUtils.getBean(UserDetailRedis.class);
    }

    /**
     * 获取用户信息
     */
    public static UserDetail getUser(){
        Long userId = getUserId();
        if(userId == null){
            return null;
        }

        UserDetail user = userDetailRedis.get(userId);
        return user;
    }

    /**
     * 获取用户ID
     */
    public static Long getUserId() {
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        if(request == null){
            return null;
        }

        String userId = request.getHeader(Constant.USER_KEY);
        if(StringUtils.isBlank(userId)){
            return null;
        }
        return Long.parseLong(userId);
    }

    /**
     * 获取部门ID
     */
    public static Long getDeptId() {
        UserDetail user = getUser();
        if(user == null){
            return null;
        }

        return user.getDeptId();
    }
}
